/******************************************************************************
 * @File name   :      CommonQueryController.java
 *
 * @Author      :      guyifeng
 *
 * @Date        :      2011-6-27
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-27 ä¸Šå�ˆ09:53:40        guyifeng     1.0            Initial Version
 * 2011-9-16 ä¸‹å�ˆ02:03:00        wangzhize     1.1        è½¦è¾†è�”åŠ¨è°ƒæ•´
 * 2011-9-27 ä¸‹å�ˆ162:49:00        pxwu     1.2        äººå‘˜è¯¦ç»†è°ƒæ•´
 * 2011-12-20            wangzhize         1.3            è½¦è¾†è�”åŠ¨ï¼Œå¢žåŠ æ›´å¤šnullåˆ¤æ–­
 *****************************************************************************/
package com.cap.bts.framework.common.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cap.bts.framework.auth.util.UserAuthenticationUtils;
import com.cap.bts.framework.common.dto.EmployeeDetailDto;
import com.cap.bts.framework.common.dto.RfsAndMacDto;
import com.cap.bts.framework.common.service.ICommonQueryService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.commonfunc.ge.dealer.domain.DealerInfo;
import com.cap.bts.commonfunc.ge.dealer.dto.DealerDetailDto;
import com.cap.bts.commonfunc.ge.dealer.service.IDealerService;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.dto.CodeInfoDto;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.dto.BasePagerDto;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.BeanCopyUtil;
import com.cap.bts.framework.common.util.CodeTextUtils;
import com.cap.bts.framework.common.util.FileUtils;
import com.cap.bts.framework.common.util.Pager;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.menu.domain.Menu;
import com.cap.bts.framework.menu.service.IMenuService;
import com.cap.bts.framework.tree.Node;
import com.cap.bts.framework.usermgnt.constant.OrganizationType;
import com.cap.bts.framework.usermgnt.constant.RoleType;
import com.cap.bts.framework.usermgnt.constant.UserGroupCode;
import com.cap.bts.framework.usermgnt.constant.UserGroupType;
import com.cap.bts.framework.usermgnt.domain.EmployeeInfo;
import com.cap.bts.framework.usermgnt.domain.Organization;
import com.cap.bts.framework.usermgnt.domain.Role;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.dto.ApprovalSubmitDto;
import com.cap.bts.framework.usermgnt.dto.UserGroupDto;
import com.cap.bts.framework.usermgnt.dto.UserGroupQueryDto;
import com.cap.bts.framework.usermgnt.service.IEmployeeInfoService;
import com.cap.bts.framework.usermgnt.service.IOrganizationMgntService;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;

/**
 * controller to handler the request of pop-up some common page
 */
@Controller
@RequestMapping(value = "/common")
public class CommonQueryController extends BaseController {
	
	@Autowired
	private ICommonQueryService commonQueryService;
	
	@Autowired
	private IOrganizationMgntService organizationMgntService;
	    
    
    @Resource(name = "menuService")
    private IMenuService menuService;
    
    @Autowired
    private ICodeMapping codeMapping;
    
    @Autowired
    private IEmployeeInfoService employeeService;
    
    @Autowired
    private IUserMgntService userMgntService;
    
    @Autowired
    ICodeMapping codeMappingService;
	
    
    @Autowired
    private IDealerService dealerService;
	
    /**
	
	
	
	
	 /**
     * æŸ¥è¯¢ç”¨æˆ·ç¾¤
     * @Date        :      2011-6-20
     * @return
     */
    @RequestMapping(value = "/getDefaultUserGroupPage",method = RequestMethod.GET)
    public String getDefaultUserGroupPage(@RequestParam("outputid") String outputid,Model model) throws AppException{
        User user = this.getCurrentUser();
        UserGroupQueryDto userGroupDto = new UserGroupQueryDto();
        userGroupDto.setUserGroupType(UserGroupType.DEALER.getValue());
        userGroupDto.setBrandId(user.getBrandId());
        List<UserGroupDto> userGroups = userMgntService.getUserGroupDtos(userGroupDto);
        model.addAttribute("outputid", outputid);
        model.addAttribute("userGroups", userGroups);
        model.addAttribute("userGroupQueryDto", userGroupDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, userGroupDto.getPager());
        return "common/query_usergroup";
        
    }
    
    /**
     * ç»�é”€å•†å²—ä½�
     * @Date        :      2011-6-27
     * @param outputid String 
     * @param model Model
     * @return url String 
     * @throws AppException all appException
     */
    @RequestMapping(value = "/getDefaultUserGroupDealer",method = RequestMethod.GET)
    public String getDefaultUserGroupDealer(@RequestParam("outputid") String outputid,Model model) throws AppException{
        UserGroupQueryDto userGroupDto = new UserGroupQueryDto();
        userGroupDto.setUserGroupType(UserGroupType.DEALER.getValue());
        List<UserGroupDto> userGroups = userMgntService.getUserGroupDtos(userGroupDto);
        model.addAttribute("outputid", outputid);
        model.addAttribute("userGroups", userGroups);
        model.addAttribute("userGroupQueryDto", userGroupDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, userGroupDto.getPager());
        return "common/query_usergroup";
        
    }
    
    /**
     * æŸ¥è¯¢ç”¨æˆ·ç¾¤
     * @Date        :      2011-6-20
     * @return
     * @throws AppException 
     */
    @RequestMapping(value = "/getUserGroup",method = RequestMethod.POST)
    public String getUserGroup(@RequestParam("outputid") String outputid,UserGroupQueryDto dto,Model model) throws AppException{
    	dto.setBrandId(getCurrentUser().getBrandId());
        List<UserGroupDto> userGroups = userMgntService.getUserGroupDtos(dto);
        model.addAttribute("userGroups", userGroups);
        model.addAttribute("outputid", outputid);
        model.addAttribute("userGroupQueryDto", dto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, dto.getPager());
        return "common/query_usergroup";
    }
    
    /**
     * æŸ¥è¯¢è§’è‰²
     * @Date        :      2011-6-20
     * @return
     */
    @RequestMapping(value = "/getDefaultRolePage",method = RequestMethod.GET)
    public String getDefaultRolePage(@RequestParam("outputid") String outputid,Model model) throws AppException{
        BasePagerDto pagerDto = new BasePagerDto();
        
        List<Role> roles = commonQueryService.getRoleWithPager(RoleType.DEALER, pagerDto.getPager());
        model.addAttribute("outputid", outputid);
        model.addAttribute("roles", roles);
        model.addAttribute("pagerDto", pagerDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, pagerDto.getPager());
        return "common/query_role";
        
    }
    
    /**
     * æŸ¥è¯¢è§’è‰²
     * @Date        :      2011-6-20
     * @return
     * @throws AppException 
     */
    @RequestMapping(value = "/getRoles",method = RequestMethod.POST)
    public String getRoles(@RequestParam("outputid") String outputid,BasePagerDto pagerDto,Model model) throws AppException{
        
        List<Role> roles = commonQueryService.getRoleWithPager(RoleType.DEALER, pagerDto.getPager());
        model.addAttribute("roles", roles);
        model.addAttribute("outputid", outputid);
        model.addAttribute("pagerDto", pagerDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, pagerDto.getPager());
        return "common/query_role";
    }
    
    /**
     * æŸ¥è¯¢ç»„ç»‡
     * @Date        :      2011-6-20
     * @return
     */
    @RequestMapping(value = "/getDefaultOrgPage",method = RequestMethod.GET)
    public String getDefaultOrgPage(@RequestParam("outputid") String outputid,Model model) throws AppException{
        BasePagerDto pagerDto = new BasePagerDto();
        User user = this.getCurrentUser();
        Organization dealerOrg = user.getEmployerOrg();
        if (dealerOrg != null) {
            List<Organization> orgs = organizationMgntService.getChildOrganizationsByOrgCode(dealerOrg.getOrgCode());
            if(orgs!=null && orgs.size()>0){
            	Pager pager = pagerDto.getPager();
            	pager.setTotalSize(orgs.size());
            	pager.setTotalPages(1);
            }
            model.addAttribute("orgs", orgs);
        }
        model.addAttribute("outputid", outputid);        
        model.addAttribute("pagerDto", pagerDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, pagerDto.getPager());
        return "common/query_organization";
        
    }
    
    /**
     * æŸ¥è¯¢ç»„ç»‡
     * @Date        :      2011-6-20
     * @return
     * @throws AppException 
     */
    @RequestMapping(value = "/getOrgs",method = RequestMethod.POST)
    public String getOrgs(@RequestParam("outputid") String outputid,BasePagerDto pagerDto,Model model) throws AppException{
        
        Integer[] orgTypes = new Integer[]{OrganizationType.MAC,OrganizationType.RFS,
            OrganizationType.RPC,OrganizationType.CENTRAL};
        List<Organization> orgs = commonQueryService.getOrganizationWithPager(orgTypes, pagerDto.getPager());
        model.addAttribute("orgs", orgs);
        model.addAttribute("outputid", outputid);
        model.addAttribute("pagerDto", pagerDto);
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, pagerDto.getPager());
        return "common/query_organization";
    }

    /**
     * @Date        :      2011-6-20
     * @return
     */
    @RequestMapping(value = "/toUserGroupAndOrgPage", method = RequestMethod.GET)
    public String getUserGroupAndOrgPage(@RequestParam("ownerId") String ownerId,Model model) throws AppException {
        
        UserGroupQueryDto userGroupDto = new UserGroupQueryDto();
        userGroupDto.setUserGroupType(UserGroupType.DEALER.getValue());
        userGroupDto.setBrandId(getCurrentUser().getBrandId());
        //List<UserGroup> userGroups = commonQueryService.getUserGroups(userGroupDto);
        List<UserGroup> userGroups = userMgntService.getUserGroups(userGroupDto);
       
        model.addAttribute("ownerId", ownerId);
        model.addAttribute("userGroups", userGroups);
       
        return "/common/select_usergroup_role";
    }
    
    /**
     * æŸ¥è¯¢ç»„ç»‡
     * @Date        :      2011-6-21
     * @param ownerId
     * @param usrGrpCode
     * @param model
     * @param res
     * @return
     * @throws AppException
     * @throws IOException
     */
    @RequestMapping(value = "/getOrgByUsrGrpCode", method = RequestMethod.GET)
    public String getOrganizationByUsrGrpCode(@RequestParam("ownerId") String ownerId,@RequestParam("usrGrpCode") String usrGrpCode ,
        Model model, HttpServletResponse res) throws AppException, IOException{
        
        List<Organization> orgs = organizationMgntService.getOrganizationsByUsrGrpAndOwnerId(usrGrpCode, ownerId);
        
        
        //just for test
//        Organization org1 = new Organization();
//        org1.setId(1l);
//        org1.setOrgCode("1305276091745");
//        org1.setOrgName("daqu1");
//        orgs.add(org1);
        //just for test
        
        if(orgs != null && orgs.size() > 0){
            StringBuffer sb = new StringBuffer();
            for (Organization org : orgs) {
                String parentOrgCOde = org.getParentOrgCode();
                Organization parentOrg = organizationMgntService.getOrganizationByOrgCode(parentOrgCOde);
                List<User> users = organizationMgntService.getManagerUserByOrgCodeAndUsrGrpCode(usrGrpCode, org.getOrgCode());
                
                StringBuilder userStr = new StringBuilder();
                if(users != null && users.size() > 0){
                    for(int i = 0;i<users.size();i++){
                        User user = users.get(i);
                        userStr.append(user.getName()+",");
                    }
                    if(userStr.length() > 0){
                        userStr.deleteCharAt(userStr.length()-1);
                    }
                }
                
                sb.append("<tr>");
                sb.append("<td class='center'>");
                sb.append("<input type='radio' id='orgCodeRad' value='"
                    + org.getOrgCode() + "' name= 'orgCodeRad' class='validate[required]'/>");
                sb.append("</td>");
                sb.append("<td>" + org.getOrgName() + "</td>");
                sb.append("<td>" + userStr + "</td>");
                if (parentOrg != null){
                    sb.append("<td>" + parentOrg.getOrgName() + "</td>");
                }else {
                    sb.append("<td>&nbsp;</td>");
                }
                
                sb.append("</tr>");
            }
            res.setCharacterEncoding("UTF-8");
            PrintWriter print = res.getWriter();
            print.print(sb.toString());
            print.close();
        }
        
        return null;
    }
    
    /**
     * æŸ¥è¯¢è�œå�•
     * @param userCode
     * 
     * @Date        :      2011-6-24
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/getMenuByUserCode")
    @ResponseBody
    public List<Node> getMenusByUserCode(@RequestParam("regionType") String regionType) throws AppException{
        List<Node> listNode = menuService.getGrantedMenuNodesByUserCode(regionType);
        return listNode;
    }
    /**
     * æ ¹æ�®UserIdèŽ·å�–ç”¨æˆ·çš„è¯¦ç»†ä¿¡æ�¯
     * @Date        :      2011-6-30
     * @param userId long 
     * @return String  
     * @throws AppException 
     */
    @RequestMapping(value = "/getEmployeeDetailByUserId")
    public String getEmployeeDetailByUserId(@RequestParam("userId")  long userId, Model model) throws AppException{
      
        
     User user = userMgntService.getUserByUserId(userId);
     EmployeeInfo employeeInfo = employeeService.getEmployeeInfoById(user.getEmployeeId());
     EmployeeDetailDto employeeDetailDto = new  EmployeeDetailDto();  
     BeanCopyUtil.beanCopyProperties(employeeInfo, employeeDetailDto);
     employeeDetailDto.setEmployeeId(employeeInfo.getId());
     employeeDetailDto.setCertificateId(employeeInfo.getCertificateType());
     employeeDetailDto.setCertificateCode(employeeInfo.getCertificateNo());
     employeeDetailDto.setEmployeeCode(employeeInfo.getEmployeeCode());
     DealerDetailDto dealerDetailDto = dealerService.getDealerById(employeeInfo.getDealerId());
     if (dealerDetailDto != null){
         employeeDetailDto.setDealerCode(dealerDetailDto.getDealerCode());  
     }
     if (employeeDetailDto.getUserGroupOrgList() != null){
         com.cap.bts.framework.common.dto.UserGroupOrgDto userGroupOrgDto = employeeDetailDto.getUserGroupOrgList().get(0);
         employeeDetailDto.setUserGroupCode(userGroupOrgDto.getUserGroupCode());
         if (userGroupOrgDto.getUserGroupCode().equals(UserGroupCode.SALECONSULTANT.getValue()) 
        		 || userGroupOrgDto.getUserGroupCode().equals(UserGroupCode.TELESALESPERSON.getValue())) {
        	 model.addAttribute("isSalesPerson", CommonConstants.YES);
         }
     }
     model.addAttribute("employeeDetailDto", employeeDetailDto);
     model.addAttribute("gender", codeMappingService.getCodeValueById(employeeDetailDto.getGenderId()));
     model.addAttribute("education", codeMappingService.getCodeValueById(employeeDetailDto.getEducationId()));
     model.addAttribute("certificateType", codeMappingService.getCodeValueById(employeeDetailDto.getCertificateId()));
     model.addAttribute("marriage", codeMappingService.getCodeValueById(employeeDetailDto.getMarriageId()));
     model.addAttribute("workStatus", CodeTextUtils.getText("Employee.WorkStatus", String.valueOf(employeeDetailDto.getEmploymentStatusId())));
     model.addAttribute("saleConsultLevel", codeMappingService.getCodeValueById(employeeDetailDto.getSaleConsultLevel()));
     model.addAttribute("exportData", CodeTextUtils.getText("EmployeeInfo.ExportData", String.valueOf(employeeDetailDto.getExportData())));
     model.addAttribute("isBrandTraining", CodeTextUtils.getText("EmployeeInfo.yesOrNo", String.valueOf(employeeDetailDto.getIsBrandTraining())));
     model.addAttribute("hasDriverLicense", CodeTextUtils.getText("EmployeeInfo.yesOrNo", String.valueOf(employeeDetailDto.getHasDriverLicense()))); 
    
     return "/common/employeeDmsDetail";
    }
    
    /**
     * @Date        :      2011-12-7
     * @param userGroupCode
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/getMenuByUserGroupCode")
    @ResponseBody
    public  List<Node> getMenuByUserGroupCode(@RequestParam("regionType") String regionType) throws AppException{
        User curUser= this.getCurrentUser();
        List<Role> roleList =  userMgntService.getRolesByUsrGrpCode(regionType, curUser.getBrandId());
        Set<Menu> menuSet = new LinkedHashSet<Menu>();
        List<Menu> menuList = new ArrayList<Menu>();
        for (int i = 0, size= roleList.size(); i < size; i++) {
            
            Role role = roleList.get(i);
            menuSet.addAll(menuService.getGrantedMenusByRoleCode(role.getRoleCode()));
        }
        Iterator<Menu> ite = menuSet.iterator();
        while (ite.hasNext()) {
        	Menu menu = ite.next();
        	menuList.add(menu);
        }
        
       return menuService.buildMenuTree(menuList, 0);
    }
    
        
    /**
     * æŸ¥è¯¢RFS
     * @author guo liang
     * @Date        :      2011-8-29
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/getAllRFS/{id}")
    @ResponseBody
    public List<Map<String,String>> getAllRFS(@PathVariable("id") Long id) throws AppException{
    	List<Organization> orgList = organizationMgntService.getOrgByOrgType(OrganizationType.RFS,id);
    	List<Map<String,String>> orgs = new ArrayList<Map<String,String>>();
    	Map<String,String> map = null;
    	for(Organization org: orgList){
            map = new HashMap<String,String>(); 
            map.put("text", org.getOrgName());
            map.put("value", org.getOrgCode());
            orgs.add(map);
        }
        return orgs;
    }
    
    
    /**
     * get Mac by cityId
     * @Date        :      2012-4-9
     * @param cityId
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/getMacsByCityId/{cityId}")
    @ResponseBody
    public List<RfsAndMacDto> getMacByCityId(@PathVariable("cityId") Long cityId) throws AppException{
        
        List<RfsAndMacDto> resultList = new ArrayList<RfsAndMacDto>();
        RfsAndMacDto rfsAndMacDto = null;
        User currentUser = this.getCurrentUser();
        //æ ¹æ�®cityId å’ŒbrandIdæŸ¥è¯¢æ‰€æœ‰çš„MAC
        List<Organization> macOrgs = organizationMgntService.getMacOrgsByCityIdAndBrandId(cityId, currentUser.getBrandId());
        //é��åŽ†macOrgsç»„è£…RfsAndMacDto List
        for (Organization macOrg : macOrgs) {
            rfsAndMacDto = new RfsAndMacDto();
            rfsAndMacDto.setMacId(macOrg.getId());
            rfsAndMacDto.setMacCode(macOrg.getOrgCode());
            rfsAndMacDto.setMacName(macOrg.getOrgName()); 
            //æ ¹æ�®preantCodeæŸ¥è¯¢çˆ¶Org
            Organization rfsOrg = organizationMgntService.getOrganizationByOrgCode(macOrg.getParentOrgCode());
            rfsAndMacDto.setRfsId(rfsOrg.getId());
            rfsAndMacDto.setRfsCode(rfsOrg.getOrgCode());
            rfsAndMacDto.setRfsName(rfsOrg.getOrgName());
            resultList.add(rfsAndMacDto);
        }
        return resultList;
    } 
    
   
    /**
     *æŸ¥è¯¢MAC
     * @author guo liang
     * @Date        :      2011-8-29
     * @return
     * @throws AppException                                       
     */
    @RequestMapping(value = "/getMACByRFS/{code}")
    @ResponseBody
    public List<Map<String,String>> getMACByRFS(@PathVariable("code") String orgCode) throws AppException{
    	List<Map<String,String>> orgs = new ArrayList<Map<String,String>>();
    	if(orgCode == null || orgCode.equals("")){
    		return orgs;
    	}
    	List<Organization> orgList = organizationMgntService.getAllChildOrganizationsByOrgCode(orgCode);
    	
    	Long dealerId = this.getDealerId();
    	List<Organization> srcOrgList = organizationMgntService.getMACOrgsByDealerId(dealerId);
    	Map<String,String> map = null;
    	for(Organization org: orgList){
    		boolean isExist = false;
    		if(srcOrgList != null && srcOrgList.size() != 0 && org.getParentOrgCode().equals(srcOrgList.get(0).getParentOrgCode())){
    			for(Organization srcOrg : srcOrgList){
    				if(srcOrg.getId().longValue() == org.getId().longValue()){
    					isExist = true;
    					break;
    				}
    			}
    		}
    		if(isExist == false){
    			map = new HashMap<String,String>();
	            map.put("text", org.getOrgName());
	            map.put("value", String.valueOf(org.getId()));
	            orgs.add(map);
    		}
        }
    	return orgs;
    }
    
    /**
     * æŸ¥è¯¢MAC
     * @author guo liang
     * @Date        :      2011-8-29
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/getMACByDealer")
    @ResponseBody
    public List<Map<String,String>> getMACByDealer()throws AppException{
    	Long dealerId = this.getDealerId();
    	List<Organization> orgList = organizationMgntService.getMACOrgsByDealerId(dealerId);
    	List<Map<String,String>> orgs = new ArrayList<Map<String,String>>();
    	Map<String,String> map = null;
    	for(Organization org: orgList){
            map = new HashMap<String,String>();
            map.put("text", org.getOrgName());
            map.put("value", String.valueOf(org.getId()));
            orgs.add(map);
        }
    	return orgs;
    }
    


    /**
     * èŽ·å�–åœ°åŒºè�”åŠ¨ä¸‹æ‹‰æ¡†çš„å€¼
     * 
     * @Date : 2011-6-3
     * @param id
     *            String
     * @param response HttpServletResponse
     * @return String
     * @throws AppException 
     * @throws IOException 
     */
    @RequestMapping(value = "/getCodeValue/{id}")
    @ResponseBody
    public List<CodeInfo> getCodeValue(@PathVariable("id") long id, HttpServletResponse response)
        throws AppException, IOException {
        List<CodeInfo> list = new ArrayList<CodeInfo>();
        CodeInfoDto codeInfoDto = codeMapping.getCodeInfoDtoById(id);
        if(codeInfoDto != null){
            list = codeMapping.getCodeInfoByParentCode(codeInfoDto.getCode());
        }
        return list;
    }
    
    /**
     * æ ¹æ�®ç»�é”€å•†codeåˆ¤æ–­è¯¥ç»�é”€å•†æ˜¯å�¦å­˜åœ¨
     * 
     * @author Wu Bin
     * @Date        :      2011-9-26
     * @param dealerCode String 
     * @param model Model 
     * @param response HttpServletResponse
     * @return null 
     * @throws AppException all appException 
     * @throws IOException all ioException 
     */
    @RequestMapping(value = "/isexistsdealer/{dealerCode}")
    public String deleteBuicJumpItemAndOption(@PathVariable("dealerCode") String dealerCode,
        Model model, HttpServletResponse response) throws AppException, IOException {
        boolean bl = false;
        DealerInfo dealer = dealerService.getDealerByDealerCode(dealerCode);
        if (dealer != null) {
            bl = true;
        }
        ServletOutputStream out = response.getOutputStream();
        response.setCharacterEncoding("UTF-8");
        out.print(bl + "");
        return null;
    }
    
    /**
     * æŸ¥è¯¢Code Options
     * @Date        :      2011-12-7
     * @param id
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/getcodeoptions")
    @ResponseBody
    public List<Map<String,String>> getCodeOptionsByParentCode(@RequestParam("id") long id) throws AppException{
        List<Map<String,String>> returnCodes = new ArrayList<Map<String,String>>();
        
        CodeInfo parentCode = codeMapping.getCodeInfoById(id);
        if(null == parentCode){
            return returnCodes;
        }
        List<CodeInfo> childCodes = codeMapping.getCodeInfoByParentCode(parentCode.getCode());
        if(null != childCodes){
            for(CodeInfo childCode : childCodes){
                Map<String,String> optionMap = new HashMap<String, String>();
                optionMap.put("text", childCode.getValue());
                optionMap.put("value", String.valueOf(childCode.getId()));
                returnCodes.add(optionMap);
            }
        }
        
        return returnCodes;
    }
    
    /**
     * 
     * @Date        :      Dec 9, 2011
     * @param session
     * @return
     */
    @RequestMapping(value = "/refreshsession")
    @ResponseBody
    public boolean refreshSession(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        User user = getCurrentUser();
        session.setAttribute("userSession", user);
        UserAuthenticationUtils.setLoginToCookie(request, response, user.getUserCode());
        System.out.print("refresh session!");
        return true;
    }
    
    @RequestMapping(value = "/getEmployeeApproveDetailByUserId")
    public String getEmployeeApproveDetailByUserId(@RequestParam("userId")  long userId, Model model) throws AppException{
      
        
     User user = userMgntService.getUserByUserId(userId);
     EmployeeInfo employeeInfo = employeeService.getEmployeeInfoById(user.getEmployeeId());
     EmployeeDetailDto employeeDetailDto = new  EmployeeDetailDto();  
     BeanCopyUtil.beanCopyProperties(employeeInfo, employeeDetailDto);
     employeeDetailDto.setEmployeeId(employeeInfo.getId());
     employeeDetailDto.setCertificateId(employeeInfo.getCertificateType());
     employeeDetailDto.setCertificateCode(employeeInfo.getCertificateNo());
     employeeDetailDto.setEmployeeCode(employeeInfo.getEmployeeCode());
     if(Utils.notEmpty(employeeInfo.getPhotoUrl())){
	     String photoUrl = FileUtils.getDownloadUrl(FileUtils
	         .getValue(CommonConstants.EMPLOYEE_PHOTO_ODULE_NAME), employeeInfo.getPhotoUrl());
	     employeeDetailDto.setPhotoUrl(photoUrl);
     }
     DealerDetailDto dealerDetailDto = dealerService.getDealerById(employeeInfo.getDealerId());
     if (dealerDetailDto != null){
         employeeDetailDto.setDealerCode(dealerDetailDto.getDealerCode());  
     }
     //commonQueryService.getEmployeeDetailOrgAndUserGroupAndRole(employeeDetailDto, user);
     
     if (employeeDetailDto.getUserGroupOrgList() != null){
         
     }
     model.addAttribute("employeeDetailDto", employeeDetailDto);
     model.addAttribute("gender", codeMappingService.getCodeValueById(employeeDetailDto.getGenderId()));
     model.addAttribute("education", codeMappingService.getCodeValueById(employeeDetailDto.getEducationId()));
     model.addAttribute("certificateType", codeMappingService.getCodeValueById(employeeDetailDto.getCertificateId()));
     model.addAttribute("marriage", codeMappingService.getCodeValueById(employeeDetailDto.getMarriageId()));
     model.addAttribute("workStatus", CodeTextUtils.getText("Employee.WorkStatus", String.valueOf(employeeDetailDto.getEmploymentStatusId())));
     model.addAttribute("saleConsultLevel", codeMappingService.getCodeValueById(employeeDetailDto.getSaleConsultLevel()));
     model.addAttribute("exportData", CodeTextUtils.getText("EmployeeInfo.ExportData", String.valueOf(employeeDetailDto.getExportData())));
     model.addAttribute("isBrandTraining", CodeTextUtils.getText("EmployeeInfo.yesOrNo", String.valueOf(employeeDetailDto.getIsBrandTraining())));
     model.addAttribute("hasDriverLicense", CodeTextUtils.getText("EmployeeInfo.yesOrNo", String.valueOf(employeeDetailDto.getHasDriverLicense()))); 
     //get gdms webService
    // ApprovalUserGrpAppResultDto wsResultDto=commonQueryService.getApproveRuleListByEmployeeCode(employeeInfo.getEmployeeCode());
//     if(wsResultDto.getHisApprovalRuleList()!=null && wsResultDto.getHisApprovalRuleList().size()>0){
//    	 
//    	 model.addAttribute("hisApproveList", wsResultDto.getHisApprovalRuleList());
//     }
//     if(wsResultDto.getCurApprovalRuleList()!=null && wsResultDto.getCurApprovalRuleList().size()>0){
//    	 model.addAttribute("curApproveList", wsResultDto.getCurApprovalRuleList());
//     }
     return "/common/employeeApproveDetail";
    }
    
    
    
    @RequestMapping(value = "/getApproveEmployeeDetailByUserId")
    public String getApproveEmployeeDetailByUserId(@RequestParam("userId")  long userId, Model model) throws AppException{
      
        
     User user = userMgntService.getUserByUserId(userId);
     EmployeeInfo employeeInfo = employeeService.getEmployeeInfoById(user.getEmployeeId());
     EmployeeDetailDto employeeDetailDto = new  EmployeeDetailDto();  
     BeanCopyUtil.beanCopyProperties(employeeInfo, employeeDetailDto);
     employeeDetailDto.setEmployeeId(employeeInfo.getId());
     employeeDetailDto.setCertificateId(employeeInfo.getCertificateType());
     employeeDetailDto.setCertificateCode(employeeInfo.getCertificateNo());
     employeeDetailDto.setEmployeeCode(employeeInfo.getEmployeeCode());
     if(Utils.notEmpty(employeeInfo.getPhotoUrl())){
	     String photoUrl = FileUtils.getDownloadUrl(FileUtils
	         .getValue(CommonConstants.EMPLOYEE_PHOTO_ODULE_NAME), employeeInfo.getPhotoUrl());
	     employeeDetailDto.setPhotoUrl(photoUrl);
     }
     DealerDetailDto dealerDetailDto = dealerService.getDealerById(employeeInfo.getDealerId());
     if (dealerDetailDto != null){
         employeeDetailDto.setDealerCode(dealerDetailDto.getDealerCode());  
     }
  //   commonQueryService.getEmployeeDetailOrgAndUserGroupAndRole(employeeDetailDto, user);
     
     if (employeeDetailDto.getUserGroupOrgList() != null){
         
     }
     model.addAttribute("employeeDetailDto", employeeDetailDto);
     model.addAttribute("gender", codeMappingService.getCodeValueById(employeeDetailDto.getGenderId()));
     model.addAttribute("education", codeMappingService.getCodeValueById(employeeDetailDto.getEducationId()));
     model.addAttribute("certificateType", codeMappingService.getCodeValueById(employeeDetailDto.getCertificateId()));
     model.addAttribute("marriage", codeMappingService.getCodeValueById(employeeDetailDto.getMarriageId()));
     model.addAttribute("workStatus", CodeTextUtils.getText("Employee.WorkStatus", String.valueOf(employeeDetailDto.getEmploymentStatusId())));
     model.addAttribute("saleConsultLevel", codeMappingService.getCodeValueById(employeeDetailDto.getSaleConsultLevel()));
     model.addAttribute("exportData", CodeTextUtils.getText("EmployeeInfo.ExportData", String.valueOf(employeeDetailDto.getExportData())));
     model.addAttribute("isBrandTraining", CodeTextUtils.getText("EmployeeInfo.yesOrNo", String.valueOf(employeeDetailDto.getIsBrandTraining())));
     model.addAttribute("userGroupCode",user.getUserGroup().getUserGroupCode());
     model.addAttribute("orgCode",user.getEmployerOrg().getOrgCode());
     model.addAttribute("employeeStatus",employeeInfo.getEmploymentStatusId());
     model.addAttribute("hasDriverLicense", CodeTextUtils.getText("EmployeeInfo.yesOrNo", String.valueOf(employeeDetailDto.getHasDriverLicense()))); 
     ApprovalSubmitDto submitDto=new ApprovalSubmitDto();
     model.addAttribute("submitDto",submitDto);
     return "/common/approveEmployeeDetail";
    }
}
